package com.example.dell.fastshopping.user.bank;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.network.http.BaseResponse;
import com.example.dell.fastshopping.utils.DensityUtil;
import com.example.dell.fastshopping.views.BaseListActivity;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.w3c.dom.Text;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ${YSH} on 2019/5/7.
 * 描述        ${TODO}
 * <p>
 * 更新者       $author$
 * 更新时间     $Data$
 * 描述         ${TODO}
 */
public class BankActivity extends BaseListActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.right_text)
    TextView right_text;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.nodata)
    LinearLayout nodata;
    @BindView(R.id.refresh)
    TwinklingRefreshLayout refresh;
    private BankModel model;
    private List<BankCard> mList;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_banck);
        ButterKnife.bind(this);

        super.initData();
        initView();
    }

    private void initView() {
        title.setText("我的银行卡");

        right_text.setVisibility(View.VISIBLE);
        model = ViewModelProviders.of(this).get(BankModel.class);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.addItemDecoration(new DividerItemDecoration(BankActivity.this, DividerItemDecoration.VERTICAL));
        SwipeRecyclerView swipeRecyclerView = findViewById(R.id.rv);

        // 创建菜单：
        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
                createMenu2(rightMenu);
            }
        };
        // 设置监听器。
        swipeRecyclerView.setSwipeMenuCreator(mSwipeMenuCreator);
        // 菜单点击监听。
        swipeRecyclerView.setOnItemMenuClickListener(new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int position) {
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu();
                int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
                if (menuPosition == 0) {
                    editItem(position);
                } else {
                    deleteItem(position);
                }
            }
        });
    }

    private void createMenu2(SwipeMenu menu) {
        SwipeMenuItem item1 = new SwipeMenuItem(
                BankActivity.this);
        item1.setBackground(new ColorDrawable(getResources().getColor(R.color.yellow_swipe)));
        item1.setWidth(DensityUtil.dp2px(BankActivity.this, 100));
        item1.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        // item1.setIcon(R.drawable.ic_action_important);
        item1.setText("编辑");
        // set item title fontsize
        item1.setTextSize(17);
        // set item title font color
        item1.setTextColor(Color.WHITE);
        menu.addMenuItem(item1);

        SwipeMenuItem item2 = new SwipeMenuItem(
                BankActivity.this);
        item2.setBackground(new ColorDrawable(getResources().getColor(R.color.myRed)));
        item2.setWidth(DensityUtil.dp2px(BankActivity.this, 100));
        item2.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        // item2.setIcon(R.drawable.ic_action_important);
        item2.setText("删除");
        // set item title fontsize
        item2.setTextSize(17);
        // set item title font color
        item2.setTextColor(Color.WHITE);
        menu.addMenuItem(item2);
    }

    @Override
    protected void onResume() {
        super.onResume();
        pageNum = 1;
        pageSize = 15;
        getNetData(1, 15);
    }

    @Override
    protected void getNetData(final int page, int pageSize) {
        model.getMyBanlCard().observe(this, new Observer<List<BankCard>>() {
            @Override
            public void onChanged(@Nullable List<BankCard> bankCards) {
                if (page == 1) {
                    mList = bankCards;
                } else {
                    mList.addAll(bankCards);
                }
                loadFinsh();
                if (mList.size() > 0) {
                    nodata.setVisibility(View.GONE);
                } else {
                    nodata.setVisibility(View.VISIBLE);
                }

                RecyclerView.Adapter adapter = rv.getAdapter();
                if (adapter == null) {
                    rv.setAdapter(new MyAdapter());
                } else {
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    protected TwinklingRefreshLayout getRefreshLayout() {
        return refresh;
    }

    @OnClick({R.id.back, R.id.right_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right_text:
                Intent intent = new Intent(this, AddBankCardActivity.class);
                intent.putExtra("action", "add");
                startActivity(intent);
                break;
        }
    }

    private class MyAdapter extends RecyclerView.Adapter<MyHolder> {
        @NonNull
        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(BankActivity.this).inflate(R.layout.item_bank, viewGroup, false);
            return new MyHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyHolder myHolder, int i) {
            BankCard bankCard = mList.get(i);
            String bank = bankCard.getBank();
            myHolder.name.setText(bank);
            if ("农业银行".equals(bank)) {
                myHolder.icon.setImageResource(R.mipmap.nongyeyinhang);
            } else if ("建设银行".equals(bank)) {
                myHolder.icon.setImageResource(R.mipmap.jiansheyinhang);
            } else if ("招商银行".equals(bank)) {
                myHolder.icon.setImageResource(R.mipmap.zhaoshangyinhang);
            }
            String cardId = bankCard.getCardId();
            String s = "";
            if (cardId != null && cardId.length() > 4) {
                s = cardId.substring(cardId.length() - 4, cardId.length());
            }
            myHolder.introduce.setText("尾号：" + s);

        }

        @Override
        public int getItemCount() {
            return mList.size();
        }
    }

    private class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public final ImageView icon;
        public final TextView name;
        public final TextView introduce;
        public final View itemBank;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.icon);
            itemBank = itemView.findViewById(R.id.item_bank);
            name = itemView.findViewById(R.id.name);
            introduce = itemView.findViewById(R.id.introduce);
        }

        @Override
        public void onClick(View v) {

        }
    }

    private void deleteItem(final int position) {
        BankCard bankCard = mList.get(position);
        model.deleteBankCard(bankCard.getId()).observe(this, new Observer<BaseResponse>() {
            @Override
            public void onChanged(@Nullable BaseResponse response) {
                if (response.isSuccess()) {
                    mList.remove(position);
                    rv.getAdapter().notifyDataSetChanged();
                    if (mList.size() == 0) {
                        nodata.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    private void editItem(int position) {
        Intent intent = new Intent(this, AddBankCardActivity.class);
        intent.putExtra("action", "edit");
        intent.putExtra("entity", mList.get(position));
        startActivity(intent);
    }
}
